package com.market.member.service.impl;

import cn.hutool.core.util.IdcardUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.block.channel.enums.ChannelTypeEnum;
import com.block.channel.enums.ReportTypeEnum;
import com.block.channel.service.IChannelFlowReportInfoService;
import com.block.common.annotate.RedisLock;
import com.block.common.annotate.impl.RedisLockAspect;
import com.block.common.bean.CommonParam;
import com.block.common.constant.AppRspCodeConstant;
import com.block.common.enums.BaseTypeInfoEnum;
import com.block.common.model.dto.CountInfoDTO;
import com.block.common.service.IAddressInfoService;
import com.block.common.service.IChannelCommonService;
import com.block.common.service.LogFactory;
import com.block.common.util.LocalDateUtil;
import com.block.common.vo.ResponseVo;
import com.block.db.entity.*;
import com.block.db.mapper.MemberBaseInfoMapper;
import com.block.db.mapper.MemberSourceInfoMapper;
import com.block.match.model.vo.MatchResultVO;
import com.block.match.service.IMatchApiBHandlerService;
import com.block.match.service.IMatchHandleService;
import com.market.member.enums.UserTypeEnum;
import com.market.member.model.param.UserSourceParam;
import com.market.member.model.vo.UserSourceVO;
import com.market.member.service.IMemberAreacityPositionService;
import com.market.member.service.IMemberAuthInfoService;
import com.market.member.service.IMemberSourceInfoService;
import kotlin.jvm.Synchronized;
import org.redisson.Redisson;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;

/**
 * <p>
 * 用户资质信息 服务实现类
 * </p>
 *
 * @author 
 * @since 2023-08-11
 */
@Service
public class MemberSourceInfoServiceImpl extends ServiceImpl<MemberSourceInfoMapper, MemberSourceInfo> implements IMemberSourceInfoService {

    private static final Logger log = LogFactory.getCommLog();

    @Autowired
    IAddressInfoService addressInfoService;

    @Autowired
    IMemberAuthInfoService memberAuthInfoService;
    @Resource
    MemberBaseInfoMapper memberBaseInfoMapper;
    @Autowired
    IMatchHandleService matchHandleService;
    @Autowired
    IChannelCommonService channelCommonService;
    @Autowired
    IMatchApiBHandlerService matchApiBHandlerService;
    @Autowired
    IChannelFlowReportInfoService channelFlowReportInfoService;


    @Override
    public ResponseVo updateUserSource(UserSourceParam userSourceParam, CommonParam commonParam, Integer userType){

        String redisKey = "lock::user::source::"+userSourceParam.getUid();
        try {
//            Boolean result = stringRedisTemplate.opsForValue()
//                    .setIfAbsent(redisKey, System.currentTimeMillis()+"",1, TimeUnit.HOURS);
//            if(!result){
//                return new ResponseVo(AppRspCodeConstant.SUCCESS);
//            }
            // 查询用户实名信息
            MemberAuthInfo memberAuthInfo = memberAuthInfoService.getById(userSourceParam.getUid());
            if (ObjectUtil.isEmpty(memberAuthInfo)){
                return new ResponseVo(AppRspCodeConstant.ACTION_ERROR, "未完成实名认证");
            }
//            if (!ObjectUtil.equals(memberAuthInfo.getAuthStatus(), AuthStatusEnum.SUCCESS.getValue())){
//                return new ResponseVo(AppRspCodeConstant.ACTION_ERROR, "实名认证未通过，请重试");
//            }
            if(userSourceParam.getCityCode() == null ){
                return new ResponseVo(AppRspCodeConstant.ACTION_ERROR, "未完成城市信息填写");
            }

            // 更新用户信息
            UserSourceVO userSourceVO = this.saveUserSourceInfo(memberAuthInfo, userSourceParam, commonParam);

            boolean success = userSourceVO.isSuccess();
            if (!success){
                return new ResponseVo(AppRspCodeConstant.ACTION_ERROR, "更新资质信息失败");
            }
            ChannelBaseInfo channelBaseInfo = commonParam.getChannelBaseInfo();
            if (userSourceVO.isNew() &&
                    !ObjectUtil.equals(userType, UserTypeEnum.RANDOM.getValue())){

                // 新注册的用户的资质信息统计
                CountInfoDTO countInfoDTO = new CountInfoDTO(commonParam.getChannelCode());
                countInfoDTO.setSourceCount(1);

                // 资质优质率统计
                // 房车公积金  只要有一个不是没有的话，就是优质
                if (!StrUtil.equals(userSourceParam.getHouse(), BaseTypeInfoEnum.House.hu001.getValue()) ||
                        !StrUtil.equals(userSourceParam.getCar(), BaseTypeInfoEnum.Car.car001.getValue()) ||
                        !StrUtil.equals(userSourceParam.getGjj(), BaseTypeInfoEnum.Gjj.gjj001.getValue())){
                    countInfoDTO.setSourceFineCount(1);
                }

                channelCommonService.updateChannelCount(countInfoDTO);

                // 进件进行渠道上报
                channelFlowReportInfoService.handleFlowReport(commonParam, userSourceParam.getUid(), ReportTypeEnum.SOURCE);

                /**
                 * 测试渠道不进行匹配
                 * 撞库在其他地方进行触发
                 * againMatchMerchant
                 */

                if (!StrUtil.equals(channelBaseInfo.getChannelType(), ChannelTypeEnum.TEST.getValue())){
                    // 测试渠道不进行推送
                    MemberSourceInfo memberSourceInfo = this.getById(userSourceParam.getUid());
                    //选择机构推送type
                    String type = "2";
                    List<MatchResultVO> matchResult = matchHandleService.getMatchResult0(memberSourceInfo,type);

                    if (ObjectUtil.isEmpty(matchResult)){
                        //matchResult = new MatchResultVO();
                        matchResult = Collections.emptyList();
                        for (MatchResultVO matchResultVO : matchResult) {
                            matchResultVO.setMatchSuccess(false);
                        }
                        //matchResult.setMatchSuccess(false);
                    }
                    userSourceVO.setMatchResult(matchResult);
                }else{
                    //MatchResultVO matchResult = new MatchResultVO();
                    ArrayList<MatchResultVO> matchResultVOS = new ArrayList<>();
                    for (MatchResultVO matchResult : matchResultVOS) {
                        matchResult.setMatchSuccess(false);
                    }
                    userSourceVO.setMatchResult(matchResultVOS);
                }

            }

            JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(userSourceVO));

            if (!StrUtil.equals(channelBaseInfo.getChannelType(), ChannelTypeEnum.TEST.getValue())) {
                matchApiBHandlerService.getApiBMatchResult(userSourceParam.getUid());
            }

            // 新注册用户
            return new ResponseVo(AppRspCodeConstant.SUCCESS, jsonObject);
        }catch (Exception exception){
            exception.printStackTrace();
        }
        return new ResponseVo(AppRspCodeConstant.SYS_EXCEPTION,"更新资质信息失败");
    }


    private UserSourceVO saveUserSourceInfo(MemberAuthInfo memberAuthInfo, UserSourceParam userSourceParam, CommonParam commonParam){

        /**
         * 查询
         */
        // 创建一个映射，将过滤器值与设置实体属性的操作关联起来

        boolean isNew = false;
        MemberSourceInfo memberSourceInfo = this.baseMapper.getEntityByUidLock(memberAuthInfo.getUid());
        MemberBaseInfo memberBaseInfo = memberBaseInfoMapper.getMemberInfoByUidLock(memberAuthInfo.getUid());
        Map<String, Consumer<MemberSourceInfo>> qualifications = new HashMap<>();
        MemberSourceInfo newEntity = new MemberSourceInfo();
        newEntity.setUid(memberAuthInfo.getUid());
        if (ObjectUtil.isEmpty(memberSourceInfo)){
            isNew = true;
            newEntity.setDateInfo(LocalDate.now().toString());
            newEntity.setReqIp(commonParam.getReqIp());

            ApplicationInfo applicationInfo = commonParam.getApplicationInfo();
            ChannelBaseInfo channelBaseInfo = commonParam.getChannelBaseInfo();

            newEntity.setAppCode(applicationInfo.getAppCode());
            newEntity.setAppName(applicationInfo.getAppName());

            newEntity.setChannelCode(channelBaseInfo.getChannelCode());
            newEntity.setChannelName(channelBaseInfo.getChannelName());

            newEntity.setRealname(memberAuthInfo.getRealname());
            newEntity.setIdcard(memberAuthInfo.getIdcard());
            newEntity.setMobile(memberBaseInfo.getMobile());
            newEntity.setMobileMd5(memberBaseInfo.getMobileMd5());
            newEntity.setMobileMask(memberBaseInfo.getMobile().substring(0,8));

            Integer sex = IdcardUtil.getGenderByIdCard(memberAuthInfo.getIdcard())==1?1:2;
            Integer age = IdcardUtil.getAgeByIdCard(memberAuthInfo.getIdcard());
            newEntity.setAge(age);
            newEntity.setSex(sex);
        }

        String cityCode = userSourceParam.getCityCode();
        if (StrUtil.length(cityCode) != 6){
            cityCode = StrUtil.fillAfter(cityCode, '0', 6);
        }

        AddressInfo addressInfo = addressInfoService.getById(cityCode);
        if (ObjectUtil.isNotEmpty(addressInfo)){
            newEntity.setCity(addressInfo.getCity());
            newEntity.setCityCode(addressInfo.getCityCode());
            newEntity.setProvince(addressInfo.getProvince());
            newEntity.setProvinceCode(addressInfo.getProvinceCode());
        }else{
            // TODO: 2023/8/24 消息通知

        }
        qualifications.put("hu002", entity -> entity.setHouse("hu002"));
        qualifications.put("car002", entity -> entity.setCar("car002"));
        qualifications.put("gjj002", entity -> entity.setGjj("gjj002"));
        qualifications.put("sb002", entity -> entity.setShebao("sb002"));
        qualifications.put("bx002", entity -> entity.setBaoxian("bx002"));
        qualifications.put("xyk002", entity -> entity.setXinyongka("xyk002"));
        qualifications.put("hb002", entity -> entity.setHuabei("hb002"));
        qualifications.put("bt002", entity -> entity.setBaitiao("bt002"));
        String orFilterStr = userSourceParam.getOrFilter();
        List<String> orFilter = new ArrayList<>();
        if (orFilterStr != null && !orFilterStr.trim().isEmpty()) {
            orFilter = Arrays.asList(orFilterStr.split(","));
        }
            // 设置默认值
        if(orFilter.contains("none002")){
            newEntity.setHouse("hu002");
            newEntity.setCar("car002");
            newEntity.setGjj("gjj002");
            newEntity.setShebao("sb002");
            newEntity.setBaoxian("bx002");
            newEntity.setHuabei("hb002");
            newEntity.setBaitiao("bt002");
            newEntity.setXinyongka("xyk002");

        }
        if (StrUtil.equals(orFilterStr,"none000")) {
                newEntity.setHouse("hu001");
                newEntity.setCar("car001");
                newEntity.setGjj("gjj001");
                newEntity.setShebao("sb001");
                newEntity.setBaoxian("bx001");
                newEntity.setHuabei("hb001");
                newEntity.setBaitiao("bt001");
                newEntity.setXinyongka("xyk001");
            } else {
                // 没有设置默认值
                if (!orFilter.contains("hu002")) newEntity.setHouse("hu001");
                if (!orFilter.contains("car002")) newEntity.setCar("car001");
                if (!orFilter.contains("gjj002")) newEntity.setGjj("gjj001");
                if (!orFilter.contains("sb002")) newEntity.setShebao("sb001");
                if (!orFilter.contains("bx002")) newEntity.setBaoxian("bx001");
                if (!orFilter.contains("xyk002")) newEntity.setXinyongka("xyk001");
                if (!orFilter.contains("hb002")) newEntity.setHuabei("hb001");
                if (!orFilter.contains("bt002")) newEntity.setBaitiao("bt001");
            }
        for (String filter : orFilter) {
            qualifications.getOrDefault(filter.trim(), x -> {}).accept(newEntity);
        }

        newEntity.setLoanAmount(userSourceParam.getLoanAmount());
        newEntity.setZhima(userSourceParam.getZhima());

//        newEntity.setHouse(userSourceParam.getHouse());
//        newEntity.setCar(userSourceParam.getCar());
//        newEntity.setGjj(userSourceParam.getGjj());
//        newEntity.setXinyongka(userSourceParam.getXinyongka());
//        newEntity.setBaoxian(userSourceParam.getBaoxian());

        newEntity.setShouru(userSourceParam.getShouru());
        newEntity.setXueli(userSourceParam.getXueli());
        newEntity.setGongzuo(userSourceParam.getGongzuo());
        newEntity.setYuqi(userSourceParam.getYuqi());

        //没有的字段设置默认值
        newEntity.setLoanTime("lt001");
        //newEntity.setBaitiao("bt002");
        newEntity.setWeili("wl001");
        newEntity.setYongtu("yt001");
        //newEntity.setHuabei("hb002");


        boolean saveRes = false;
        if (isNew){
            saveRes = this.save(newEntity);
            if (saveRes){
                MemberBaseInfo updateBaseInfo = new MemberBaseInfo();
                updateBaseInfo.setUid(memberAuthInfo.getUid());
                updateBaseInfo.setSourceFlag(1);
                memberBaseInfoMapper.updateById(updateBaseInfo);


            }
        }else{
            saveRes = this.updateById(newEntity);
        }
        UserSourceVO userSourceVO = new UserSourceVO();
        userSourceVO.setSuccess(saveRes);
        userSourceVO.setNew(isNew);

        return userSourceVO;
    }


}

